#include "screenshotoverlay.h"
#include <QApplication>
#include <QScreen>
#include <QPainter>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QGuiApplication>
#include <QDebug>
#include <QWindow>

ScreenshotOverlay::ScreenshotOverlay(QWidget *parent)
    : QWidget(parent), m_isSelecting(false)
{
    // 1. 获取鼠标当前所在的屏幕
    QScreen *currentScreen = QGuiApplication::screenAt(QCursor::pos());
    if (!currentScreen) {
        currentScreen = QGuiApplication::primaryScreen();
    }

    // 2. 获取屏幕的设备像素比 (Device Pixel Ratio)
    //    这就是缩放比例，例如 1.0 (100%), 1.5 (150%), 2.0 (200%)
    qreal dpr = currentScreen->devicePixelRatio();
    qDebug() << "当前屏幕的缩放比例 (DPR):" << dpr;

    // 3. 捕获整个物理屏幕的图像
    this->m_desktopImage = currentScreen->grabWindow(0);
    qDebug() << "捕获的物理图像尺寸:" << this->m_desktopImage.size();
    qDebug() << "屏幕的逻辑尺寸:" << currentScreen->geometry().size();

    // 4. 设置窗口属性
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);
    setCursor(Qt::CrossCursor);

    // 5. 让截图覆盖层只显示在当前屏幕上
    setGeometry(currentScreen->geometry());
    show();             // 使用 show() 而不是 showFullScreen() 以精确控制几何位置

    activateWindow();
    raise();
    setFocus();
}

// 绘制事件
void ScreenshotOverlay::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);

    // 绘制一个半透明的黑色遮罩
    painter.fillRect(rect(), QColor(0, 0, 0, 120));

    if (m_isSelecting)
    {
        // 鼠标坐标是逻辑坐标，我们直接在逻辑坐标系下绘制预览
        QRect selectionRect = QRect(m_startPoint, m_endPoint).normalized();

        // 计算选区在物理图像中的对应区域
        qreal dpr = windowHandle()->screen()->devicePixelRatio();
        QRect physicalSelectionRect = QRect(
                                          static_cast<int>(selectionRect.x() * dpr),
                                          static_cast<int>(selectionRect.y() * dpr),
                                          static_cast<int>(selectionRect.width() * dpr),
                                          static_cast<int>(selectionRect.height() * dpr)
                                          ).normalized();

        // 将物理图像的选区部分，绘制回逻辑尺寸的UI选区上
        painter.drawPixmap(selectionRect, this->m_desktopImage, physicalSelectionRect);

        // 绘制逻辑尺寸的边框
        painter.setPen(QPen(QColor(0, 120, 215), 2));
        painter.drawRect(selectionRect);
    }
}

// 鼠标按下事件 (逻辑坐标)
void ScreenshotOverlay::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        m_startPoint = event->pos();
        m_endPoint = m_startPoint;
        m_isSelecting = true;
    }
}

// 鼠标移动事件 (逻辑坐标)
void ScreenshotOverlay::mouseMoveEvent(QMouseEvent *event)
{
    if (m_isSelecting)
    {
        m_endPoint = event->pos();
        update();
    }
}

// 鼠标松开事件
void ScreenshotOverlay::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_isSelecting)
    {
        // 最终的选区矩形 (逻辑坐标)
        QRect selectionRect = QRect(m_startPoint, m_endPoint).normalized();

        if (selectionRect.width() > 5 && selectionRect.height() > 5)
        {
            // 【核心修正】将逻辑坐标的选区，转换为物理像素坐标
            qreal dpr = windowHandle()->screen()->devicePixelRatio();
            QRect physicalSelectionRect = QRect(
                                              static_cast<int>(selectionRect.x() * dpr),
                                              static_cast<int>(selectionRect.y() * dpr),
                                              static_cast<int>(selectionRect.width() * dpr),
                                              static_cast<int>(selectionRect.height() * dpr)
                                              ).normalized();

            // 从完整的物理像素截图中，copy出我们需要的物理像素区域
            QPixmap capturedPixmap = m_desktopImage.copy(physicalSelectionRect);

            qDebug() << "逻辑选区:" << selectionRect;
            qDebug() << "物理选区:" << physicalSelectionRect;
            qDebug() << "最终截取图像尺寸:" << capturedPixmap.size();

            emit screenshotTaken(capturedPixmap);
        }

        close();
        deleteLater();
    }
}

// 键盘事件 (保持不变)
void ScreenshotOverlay::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape)
    {
        close();
        deleteLater();
    }
}
